package org.zoomdev.zoom.dao.naming.impl;

import org.zoomdev.zoom.dao.entity.Entity;
import org.zoomdev.zoom.dao.entity.Field2ColumnMappingConfig;
import org.zoomdev.zoom.dao.naming.NameAdapter;

import java.util.HashMap;

/**
 * 通过两个map来确定改名规则
 *
 * @author jzoom
 */
public final class MapNameAdapter implements NameAdapter {
    HashMap<String, String> field2columnMap;
    HashMap<String, String> column2fieldMap;


    public MapNameAdapter(HashMap<String, String> field2columnMap,
                          HashMap<String, String> column2fieldMap) {
        super();
        this.field2columnMap = field2columnMap;
        this.column2fieldMap = column2fieldMap;
    }

    public static NameAdapter fromEntity(Entity<?> entity) {
        HashMap<String, String> field2columnMap = new HashMap<>();
        HashMap<String, String> column2fieldMap = new HashMap<>();
        for (Field2ColumnMappingConfig config : entity.getColumnConfigs()) {
            field2columnMap.put(config.getFieldName(), config.getColumnName());
            column2fieldMap.put(config.getColumnName(), config.getFieldName());
        }

        return new MapNameAdapter(field2columnMap, column2fieldMap);

    }

    @Override
    public String getFieldName(String column) {
        String field = column2fieldMap.get(column);
        if (field == null) {
            return column;
        }
        return field;
    }


    @Override
    public String getColumnName(String field) {
        String column = field2columnMap.get(field);
        if (column == null) {
            return field;
        }
        return column;
    }


}
